/*
 * friendlyForm jQuery plugin
 * ultimate combination for styling HTML forms
 *
 * Copyright 2010, OXiDE
 * This software is released under GNU General Public License Version 3
 * See http://www.friendlyform.net/license for more information.
 */

if(jQuery) (function($) {

    function positionList(fakeSelectId)
    {
        var fakeSelect = $("#select_" + fakeSelectId);
        var optionsWrapper = $("#options_" + fakeSelectId);
        var fakeSelectOffset = fakeSelect.offset();
        
        var optionsWrapperTop = fakeSelectOffset.top + fakeSelect.outerHeight(false);
        optionsWrapper.css({top : optionsWrapperTop, left : fakeSelectOffset.left});
        
    }

    function selectOption(fakeSelectId, optionId)
    {
        var fakeSelect = $("#select_" + fakeSelectId);
        var mySelect = $("select[name=" + fakeSelectId + "]");

        var value = optionId;
        value = value.replace('option_' + fakeSelectId + '_value-', '');

        mySelect.val(value);
        $("#" + optionId).addClass('selected');
        $("#" + optionId).siblings().removeClass('selected');
        fakeSelect.find('span#value_' + fakeSelectId).text($("#" + optionId).text());
    }

    $.extend($.fn, {
        friendlyDropDown: function() {
            $(this).each(function() {
                /*
                 * Building element
                 */
                var mySelect = $(this);
                var fakeSelectId = mySelect.attr('name');
                var fakeSelect = '<a href="#" id="select_' + fakeSelectId + '" class="friendlyDropDown friendlyDropDownText"><span id="value_' + fakeSelectId + '">' + mySelect.children("[selected]").text() + '</span></a>';
                mySelect.after(fakeSelect);
                mySelect.hide();
                fakeSelect = $("#select_" + fakeSelectId);

                if (false)
                {
                    var offset = mySelect.offset();
                    fakeSelect.css({top : offset.top, left : offset.left});
                }

                /*
                 * Building options list
                 */
                var selectOptions = mySelect.children('option');
                var listElements = '';
                selectOptions.each(function(index, elem) {
                    var selected = '';
                    var value = $(this).attr('value');
                    var label = $(this).text();
                    if ($(this).attr('selected'))
                        selected = ' class="selected"';
                    listElements += '<li' + selected + ' id="option_' + fakeSelectId + '_value-' + value + '">' + label + '</li>' + "\n";
                });
                var optionsWrapper = '<div id="options_' + fakeSelectId + '" class="friendlyDropDownList friendlyDropDownText">' + "\n" + '<ul>' + "\n" + listElements + '</ul>' + "\n" + '</div>';
                fakeSelect.after(optionsWrapper);
                optionsWrapper = $("#options_" + fakeSelectId);
                var options = optionsWrapper.find('li');

                /*
                 * Dimensions manipulation
                 */

                positionList(fakeSelectId);
                fakeSelect.children('span').width(optionsWrapper.width());
                if ($.browser.msie && parseInt($.browser.version) < 9)
                {
                    var tmpHtml = fakeSelect.html();
                    var newSpan = '<span id="ieFix_' + fakeSelectId + '" class="friendlyDropDownIeFix">' + tmpHtml + '</span>'
                    fakeSelect.html(newSpan);

                    newSpan = $("#ieFix_" + fakeSelectId);
                    newSpan.width(fakeSelect.width() + parseInt(fakeSelect.css('padding-right')));
                    newSpan.css('overflow','hidden');
                    fakeSelect.width(fakeSelect.innerWidth() + parseInt(fakeSelect.css('padding-right')) + parseInt(fakeSelect.css('padding-left')));
                }
                if (optionsWrapper.children('ul').outerHeight() > optionsWrapper.height() > 0)
                {
                    optionsWrapper.width(optionsWrapper.width() + 20);
                }

                /*
                 * Binding events
                 */
                $(window).bind('resize', function() {
                    return positionList(fakeSelectId);
                });

                fakeSelect.bind('focus', function() {
                    $(this).addClass('focus');
                    return false;
                });
                fakeSelect.bind('blur', function(event) {
                    $(this).removeClass('focus');
                    if(!($(event.target).parents().andSelf().is("#options_" + fakeSelectId)) && !($(event.target).parents().andSelf().is("#select_" + fakeSelectId))){
						fakeSelect.removeClass('active');
                        optionsWrapper.slideUp('fast');
					}
                });

                fakeSelect.bind('click', function() {
                    $(".friendlyDropDownList:not(#options_" + fakeSelectId + ")").hide();
                    $(".friendlyDropDown:not(#select_" + fakeSelectId + ")").removeClass('active');
                    $(this).toggleClass('active');
                    optionsWrapper.slideToggle('fast');
                    return false;
                });

                fakeSelect.bind('keydown', function(event) {
                    var current = options.filter(".selected");
                    var next;
                    switch (event.which)
                    {
                        case 38:
                            event.preventDefault();
                            if (current.index() == 0)
                            {
                                next = options.last();
                            }
                            else
                            {
                                next = current.prev();
                            }
                            selectOption(fakeSelectId, next.attr('id'));
                            break;
                        case 40:
                            event.preventDefault();
                            if (current.index() == options.last().index())
                            {
                                next = options.first();
                            }
                            else
                            {
                                next = current.next();
                            }
                            selectOption(fakeSelectId, next.attr('id'));
                            break;
                        default:

                            break;
                    }
                });

				$(window).click( function(event) {
					if(!($(event.target).parents().andSelf().is("#options_" + fakeSelectId)) && !($(event.target).parents().andSelf().is("#select_" + fakeSelectId))){
						fakeSelect.removeClass('active');
                        optionsWrapper.slideUp('fast');
					}
				});

                if ($.browser.msie && parseInt($.browser.version) < 9)
                {
                    options.hover(function() {$(this).addClass('hover');}, function() {$(this).removeClass('hover');});
                }

                options.bind('click', function() {
                    var value = $(this).attr('id');
                    selectOption(fakeSelectId, value);
                    fakeSelect.click();
                    fakeSelect.get(0).focus();
                });

                $("label[for=" + fakeSelectId + "]").bind('click', function(event) {
                    fakeSelect.get(0).focus();
                });

                optionsWrapper.hide();
            });
        },
        friendlyCheckBox: function() {
            $(this).each(function() {
                var myCheckBox = $(this);
                /*
                 * Building element
                 */
                var fakeCheckBoxId = myCheckBox.attr('id');
                var fakeCheckBox = '<a href="#" id="checkbox_' + fakeCheckBoxId + '" class="friendlyCheckBox"></a>';
                myCheckBox.after(fakeCheckBox);
                myCheckBox.hide();
                fakeCheckBox = $("#checkbox_" + fakeCheckBoxId);

                if (myCheckBox.attr('checked') == 'checked')
                {
                    fakeCheckBox.addClass('checked');
                }

                fakeCheckBox.bind('focus', function() {
                    $(this).addClass('focus');
                });
                fakeCheckBox.bind('blur', function() {
                    $(this).removeClass('focus');
                });

                fakeCheckBox.bind('click', function() {
                    if ($(this).hasClass('checked'))
                    {
                        $(this).removeClass('checked');
                        myCheckBox.attr('checked', '');
                    }
                    else
                    {
                        $(this).addClass('checked');
                        myCheckBox.attr('checked', 'checked');
                    }
                    return false;
                });

                fakeCheckBox.bind('keydown', function(event) {
                    if (event.which == '32')
                    {
                        $(this).click();
                    }
                });

                $("label[for=" + fakeCheckBoxId + "]").bind('click', function(event) {
                    fakeCheckBox.click();
                });
            });
        },
        friendlyRadio: function() {
            $(this).each(function() {
                var myRadio = $(this);
                /*
                 * Building element
                 */
                var fakeRadioId = myRadio.attr('id');
                var radioName = myRadio.attr('name');
                var fakeRadio = '<a href="#" id="radio_' + fakeRadioId + '" class="friendlyRadio ' + radioName + '"></a>';
                myRadio.after(fakeRadio);
                myRadio.hide();
                fakeRadio = $("#radio_" + fakeRadioId);

                if (myRadio.attr('checked') == 'checked')
                {
                    fakeRadio.addClass('checked');
                }

                fakeRadio.bind('focus', function() {
                    $(this).addClass('focus');
                });
                fakeRadio.bind('blur', function() {
                    $(this).removeClass('focus');
                });

                fakeRadio.bind('click', function() {
                    if ($(this).hasClass('checked'))
                    {
                        
                    }
                    else
                    {
                        $("." + radioName).removeClass('checked');
                        $(this).addClass('checked');
                        $("input[type=radio,name=" + radioName + "]").attr('checked', '');
                        myRadio.attr('checked', 'checked');
                    }
                    return false;
                });

                fakeRadio.bind('keydown', function(event) {
                    var next;
                    var radioButtons = $("." + radioName);
                    var current = radioButtons.filter("checked");
                    switch (event.which)
                    {
                        case 38:
                            event.preventDefault();
                            if (current.index() == 0)
                            {
                                next = radioButtons.last();
                            }
                            else
                            {
                                next = current.prev();
                            }
                            next.focus();
                            next.click();
                            break;
                        case 40:
                            event.preventDefault();
                            if (current.index() == radioButtons.last().index())
                            {
                                next = radioButtons.first();
                            }
                            else
                            {
                                next = current.next();
                            }
                            next.focus();
                            next.click();
                            break;
                        default:

                            break;
                    }
                });

                $("label[for=" + fakeRadioId + "]").bind('click', function(event) {
                    fakeRadio.focus();
                    fakeRadio.click();
                });
            });
        },
        friendlyForm: function(options) {
            $(this).each(function() {
                var settings = {
                    'class' : 'friendlyForm',
                    'theme' : 'default'
                };
                if (options) {
                    $.extend(settings, options);
                }

                $(this).find('select').friendlyDropDown();
                $(this).find('input[type=checkbox]').friendlyCheckBox();
                $(this).find('input[type=radio]').friendlyRadio();
                $(this).addClass(settings['class'] + ' ' + settings['theme']);
            });
        }
    });
})(jQuery);